<?php

namespace App\Http\Controllers\Member;

use App\Model\Category;
use App\Models\Archive\Archive;
use App\Models\Live\LiveCategory;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class categoryController extends Controller
{
    public function index()
    {
        $category = Category::orderBy('cate_weight','asc')->get();
        $cate_list = Category::sort($category);
        foreach($cate_list as $v){
            $v->count = Archive::where('category_id',$v->cate_id)->count();
            if(Category::where('cate_pid',$v->cate_id)->count()){
                $v->isLast = 0;
            }else{
                $v->isLast = 1;
            }
        }
        return view('member.masterCategoryList',compact('cate_list'));
    }

    public function create()
    {
        $category = Category::get();
        $cate_list = Category::sort($category);
        return view('member.masterCategoryAdd',compact('cate_list'));
    }

    public function store()
    {
        if($input = Input::except('_token','cate_background')){
            if(Input::file('cate_background')){
                $input['cate_background'] = $this->uploadBackground(Input::file('cate_background'));
            }else{
                $input['cate_background'] = '';
            }

            $input['updated_at'] = date('Y-m-d H:i:s',time());
            $rules = [
                'cate_name'=>'required',
                'cate_pid'=>'required',
                'cate_weight'=>'numeric|between:0,99',
            ];
            $message = [
                'cate_name.required'=>'栏目名不能为空！',
                'cate_name.unique'=>'栏目名重复！',
                'cate_pid.required'=>'父栏目不能为空！',
                'cate_weight.numeric'=>'栏目权重为数字',
                'cate_weight.between'=>'栏目权重在0到99之间',
            ];
            $validator = Validator::make($input,$rules,$message);
            if($validator->passes()){
                $rs = Category::create($input);
                if($rs){
                    return back()->with('msg','栏目添加成功！');
                }else{
                    return back()->with('msg','栏目添加失败！');
                }
            }else{
                return back()->withErrors($validator);
            }
        }else{
            return back()->with('errors','错误！');
        }

    }

    public function uploadBackground($file)
    {
        if($file->isValid()){
            $extension = $file->getClientOriginalExtension();
            $dir = base_path().'/public/upload/logo/'.date('Ymd',time());
            if(!is_dir($dir)){
                mkdir($dir);
            }
            $string = 'ABCDEFGHIJKLMNPQRST1234567890';
            $fileNewName = substr(str_shuffle($string),0,6).'.'.$extension;
            $file->move($dir,$fileNewName);
            $filepath = '/upload/logo/'.date('Ymd',time()).'/'.$fileNewName;
            return $filepath;
        }

    }

    public function delete($id)
    {
        if(is_numeric($id)){
            if(Category::where('cate_id',$id)->first()){
                if(Category::where('cate_pid',$id)->count()){
                    return back()->with('msg','请先删除此栏目的子栏目！');
                }else{
                    if(Category::where('cate_id',$id)->delete()){
                        return back()->with('msg','删除成功！');
                    }else{
                        return back()->with('msg','删除失败！');
                    }
                }
            }else{
                return back()->with('msg','栏目不存在！');
            }
        }else{
            return back()->with('msg','非法请求！');
        }
    }

    public function edit($id)
    {
        if(is_numeric($id)){
            $cate_info = Category::where('cate_id',$id)->first();
            if($cate_info){
                $view = view('member.masterCategoryEdit');

                $category = Category::get();
                $cate_list = Category::sort($category);

                if ($cate_info->cate_pid == 47) {
                    $lives = DB::table('lives')->get()->map(function ($live) {
                        return [
                            'live_name' => $live->name,
                            'cates' => LiveCategory::where('live_id', $live->id)->get(),
                        ];
                    });
                    $view->with('live_cate', $lives)->with('live_has', DB::table('cate_live_cate')->where('cid', $id)->pluck('live_cid')->toArray());
                }

                return $view
                    ->with('cate_info', $cate_info)
                    ->with('cate_list', $cate_list)
                ;
            }else{
                return back()->with('msg','栏目不存在！');
            }
        }else{
            return back()->with('msg','非法请求！');
        }
    }
    public function update($id)
    {
        if($input = Input::except('_token','cate_background', 'live_cate')){
            if(Input::file('cate_background')){
                $input['cate_background'] = $this->uploadBackground(Input::file('cate_background'));
            }else if($input['cate_background'] = Input::only('cate_background')){
                $input['cate_background'] = Input::get('cate_background');
            }else{
                return back()->with('errors','请上传背景！');
            }
            $input['cate_intro'] = str_replace("<p><br /></p>",'',$input['cate_intro']);
            $input['updated_at'] = date('Y-m-d H:i:s',time());
            $rules = [
                'cate_name'=>'required',
                'cate_pid'=>'required',
//                'cate_logo'=>'required',
            ];
            $message = [
                'cate_name.required'=>'栏目名不能为空！',
//                'cate_name.unique'=>'栏目名重复！',
                'cate_pid.required'=>'父栏目不能为空！',
//                'cate_logo.required'=>'请上传logo！',
            ];
            $validator = Validator::make($input,$rules,$message);
            if($validator->passes()){
                $rs = Category::where('cate_id',$id)->update($input);

                $live_cate = Input::get('live_cate');
                if(isset($live_cate)){
                    DB::table('cate_live_cate')->whereIn('live_cid', $live_cate)->delete();

                    DB::table('cate_live_cate')->insert(collect($live_cate)->map(function ($live_cid) use($id) {
                        return [
                            'cid' => $id,
                            'live_cid' => $live_cid,
                        ];
                    })->toArray());
                }
                if($rs){
                    return back()->with('msg','栏目修改成功！');
                }else{
                    return back()->with('msg','栏目修改失败！');
                }
            }else{
                return back()->withErrors($validator);
            }
        }else{
            return back()->with('errors','错误！');
        }

    }

    public function is_on()
    {
        $input = Input::except('_token');
        if($input){
            if($input['is_on']){
                $count = Category::where('is_on',1)->count();
                if($count>2){
                    return 'NotAllowed';
                }
            }
                $data['is_on'] = $input['is_on'];
                if(Category::where('cate_id',$input['cate_id'])->update($data)){
                    return 'success';
                }else{
                    return 'error1';
                }
        }else{
            return 'error2';
        }
    }
}
